package day_2023_7_to_10;

/**
 * @author haomin
 * @date 2023/08/09 23:58
 **/
public class Day_8_9 {
    class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            return buildTreeHelper(preorder, inorder, 0, preorder.length - 1);
        }

        int post = 0;
        public TreeNode buildTreeHelper(int[] pre, int [] inor, int l, int r) {
            if(post == pre.length || l > r) return null;
            TreeNode cur = new TreeNode(pre[post]);
            int index = findInInor(pre[post], inor);
            post++;
            cur.left = buildTreeHelper(pre, inor, l, index-1);
            cur.right = buildTreeHelper(pre, inor, index+1, r);
            return cur;
        }

        public int findInInor(int k, int[] inor) {
            for(int i = 0; i < inor.length; ++i)
                if(k == inor[i]) return i;
            return -1;
        }
    }
}